#!/usr/bin/python

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

# External imports
import sys
import os.path

# Internal imports
from Feedtorrent.Model import TVSerie, Season, Episode, Event

def follow(tvSerieName, publisher=None):
  tvSerie = TVSerie.select(TVSerie.q.name == tvSerieName)
  if tvSerie.count() == 1:
    tvSerie[0].publisher = publisher
    print 'TV Serie %s updated: Now followed from %s' % (tvSerieName, publisher)
    return
  if tvSerie.count() > 1:
    raise RuntimeError, 'Database corrupted, please delete it or correct it'
  tvSerie = TVSerie(name=tvSerieName, active=True, publisher=publisher)
  print 'TV Serie %s%s followed (created).' % (tvSerie.name,
      publisher and ' from %s' % publisher or '')

def unfollow(tvSerieName):
  tvSerie = TVSerie.select(TVSerie.q.name == tvSerieName)
  if tvSerie.count() == 0:
    raise RuntimeError, 'TV Serie %s not followed (deleted).' % tvSerieName
  if tvSerie.count() > 1:
    raise RuntimeError, 'Database corrupted, please delete it or correct it'
  tvSerie = list(tvSerie)[0]
  TVSerie.delete(tvSerie.id)
  print 'TV Serie %s unfollowed.' % tvSerie.name

def activate(tvSerieName):
  tvSerie = TVSerie.select(TVSerie.q.name == tvSerieName)
  if tvSerie.count() == 0:
    raise RuntimeError, 'TV Serie %s not followed.' % tvSerieName
  if tvSerie.count() > 1:
    raise RuntimeError, 'Database corrupted, please delete it or correct it'
  tvSerie = list(tvSerie)[0]
  if tvSerie.active:
    raise RuntimeError, 'TV Serie %s already activated.' % tvSerieName
  tvSerie.active = True
  print 'TV Serie %s activated.' % tvSerie.name

def deactivate(tvSerieName):
  tvSerie = TVSerie.select(TVSerie.q.name == tvSerieName)
  if tvSerie.count() == 0:
    raise RuntimeError, 'TV Serie %s not followed.' % tvSerieName
  if tvSerie.count() > 1:
    raise RuntimeError, 'Database corrupted, please delete it or correct it'
  tvSerie = list(tvSerie)[0]
  if not tvSerie.active:
    raise RuntimeError, 'TV Serie %s already deactivated.' % tvSerieName
  tvSerie.active = False
  print 'TV Serie %s deactivated.' % tvSerie.name

def listdb():
  for tvSerie in TVSerie.select():
    print 'TV Serie %s%s [%s]' % (tvSerie.name,
        tvSerie.publisher and ' from %s' % tvSerie.publisher or '',
        tvSerie.active and 'active' or \
        'inactive')
    if not tvSerie.active:
      continue
    for season in tvSerie.seasons:
      print '\tSeason %d' % season.number
      for episode in season.episodes:
        print '\t\tEpisode %d: %s' % (episode.number, episode.title)

def listevents():
  print 'feedtorrent events'
  for event in Event.select():
    print """
Title: %s
Description: %s
Date: %s
""" % (event.title, event.description,
    event.date.strftime('%H:%M:%S %d/%m/%Y'))

def subtitle(filename, language):
  from Feedtorrent.Subdownloader import download
  print 'subtitle download ends with status %d' % download(filename, language)

def describe(filename):
  from Feedtorrent.TorrentParser import Torrent
  print Torrent(filename)

if __name__ == '__main__':
  # Usage: ./%s <cmd> <args>
  # cmd "follow" <tv serie name> [publisher to follow]
  # cmd "unfollow" <tv serie name>
  # cmd "deactivate" <tv serie name>
  # cmd "activate" <tv serie name>
  # cmd "listdb"

  if len(sys.argv) < 2:
    print 'No command given.'
    sys.exit(-1)

  cmdHandler = {
    'follow': follow,
    'unfollow': unfollow,
    'activate': activate,
    'deactivate': deactivate,
    'listdb': listdb,
    'listevents': listevents,
    'subtitle': subtitle,
    'describe': describe
  }.get(sys.argv[1])

  if cmdHandler is None:
    print 'Unknown command %s.' % sys.argv[1]
    sys.exit(-1)

  try:
    cmdHandler(*sys.argv[2:])
  except Exception, msg:
    print 'ERROR: Command %s failed: %s' % (sys.argv[1], msg)

